package org.example.aop;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.core.ApplicationContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.Util.JwtUtil;
import org.example.mapper.OperateLogMapper;
import org.example.pojo.OperateLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.http.HttpRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JwtUtil jwtUtil;

    @Around("@annotation(org.example.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("记录日志");
        // 操作人ID - 当前登录员工ID
        String jwt = request.getHeader("token");
        Claims claims = jwtUtil.checkToken(jwt);
        Integer operateUserId = (Integer) claims.get("id");

        // 操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        // 操作类名
        String className = joinPoint.getTarget().getClass().getName();

        // 操作方法名
        String methodName = joinPoint.getSignature().getName();

        // 操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        // 获取系统当前时间
        long startTime = System.currentTimeMillis();
        // 调用原始目标方法运行
        Object result = joinPoint.proceed();
        // 获取系统当前时间
        long endTime = System.currentTimeMillis();

        // 方法返回值
        String returnValue = JSONObject.toJSONString(result);

        // 操作耗时
        Long costTime = endTime - startTime;

        OperateLog operatelog = new OperateLog(null, operateUserId, operateTime, className, methodName, methodParams, returnValue, costTime);
        operateLogMapper.insert(operatelog);

        log.info("AOP日志记录成功：{}", operatelog);
        return result; // 返回被增强方法执行后的结果，若没有返回值，返回null;
    }
}
